package cn.cloud9.jax_ws.client;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author OnCloud9
 * @description
 * @project JAX-WS-Client
 * @date 2022年04月23日 15:03
 */
public class HttpUrlConnectionClient {
    public static void main(String[] args) throws Exception {
        // 请求服务地址 不需要添加?WSDL参数
        URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
        // 建立链接
        final URLConnection urlConnection = url.openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        // 设置POST请求
        connection.setRequestMethod("POST");
        // 设置数据格式
        connection.setRequestProperty("content-Type", "text/xml;charset=utf-8");
        // 设置输入输出权限，connection默认没有
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // 设置请求的数据
        String payload = getXml("13879105549");

        final OutputStream outputStream = connection.getOutputStream();
        outputStream.write(payload.getBytes(StandardCharsets.UTF_8));

        // 执行发送，获取响应数据
        final int responseCode = connection.getResponseCode();
        if (responseCode != 200) throw new Exception("请求异常: 响应代码：" + responseCode);
        final InputStream inputStream = connection.getInputStream();
        final InputStreamReader reader = new InputStreamReader(inputStream);
        final BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String temp = null;
        while (null != (temp = bufferedReader.readLine())) sb.append(temp);
        System.out.println(sb);

        bufferedReader.close();
        reader.close();
        inputStream.close();
    }

    private static String getXml(String phoneNo) {
        String[] templates = {
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n",
            "  <soap:Body>\n",
            "    <getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">\n",
            "      <mobileCode>", phoneNo, "</mobileCode>\n",
            "      <userID></userID>\n",
            "    </getMobileCodeInfo>\n",
            "  </soap:Body>\n",
            "</soap:Envelope>\n"
        };
        final StringBuffer buffer = new StringBuffer();
        Arrays.asList(templates).forEach(buffer::append);
        return buffer.toString();
    }
}
